package com.cat.twoPointerTechnique;

import java.util.Arrays;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/count-the-number-of-fair-pairs/
 * @create 2025/8/3 15:58
 * @since JDK17
 */

public class Solution10 {
    public long countFairPairs(int[] nums, int lower, int upper) {
        Arrays.sort(nums);
        long ans = 0;
        int n = nums.length;
        for (int i = 0, r = n - 1, l = n - 1; i < n - 1; i++) {
            while (l > i && nums[l] < lower - nums[i]) {
                l++;
            }
            if (l == i) {
                l = i + 1;
            }
            while (r > i && nums[i] <= upper - nums[r]) {
                r--;
            }
            ans += r - l + 1;
        }
        return ans;
    }
}
